package com.dinggou.shopjb.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.dinggou.shopjb.R;


public class MoneyTextView extends AppCompatTextView {

    private String prefix = "￥";
    private int prefixColor;
    private int preSize;


    public MoneyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    public MoneyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MoneyTextView(Context context) {
        super(context);
        init(context, null);
    }

    private void init(Context context, @Nullable AttributeSet attrs) {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "din.ttf");
            setTypeface(tf);
        }

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MoneyTextView);

        prefix = ta.getString(R.styleable.MoneyTextView_prefix);
        prefixColor = ta.getInteger(R.styleable.MoneyTextView_prefix_color, R.color.color_text_ea484d);
        preSize = ta.getInteger(R.styleable.MoneyTextView_prefix_size, 12);
        String text = ta.getString(R.styleable.MoneyTextView_android_text);
        if (TextUtils.isEmpty(prefix)) {
            prefix = "￥";
        }
        if (TextUtils.isEmpty(text)) {
            text = "";
        }
        ta.recycle();
        setText(text);
    }

    public void setText(String text) {
        Spannable spanString = new SpannableString(prefix + text);
        AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(preSize, true);
        spanString.setSpan(sizeSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanString.setSpan(new ForegroundColorSpan(prefixColor), 0, prefix.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        setText(spanString);
    }
}
